<?php
class Shangku_Orderpayment_Model_Observer
{
	const XML_PATH_EMAIL_TEMPLATE = 'orderpayment/email/email_template';
	const XML_PATH_EMAIL_SENDER = 'orderpayment/email/email_sender';

	public function sendOrderpaymentEmail($observer)
	{		
		$order = $observer->getEvent()->getOrder();
		if(!$order){
			return $this;
		}
		
		$storeId = $order->getStoreId();
		
		// Start store emulation process
		$appEmulation = Mage::getSingleton('core/app_emulation');
		$initialEnvironmentInfo = $appEmulation->startEnvironmentEmulation($storeId);
		
		try {
			// Retrieve specified view block from appropriate design package (depends on emulated store)
			$paymentBlock = Mage::helper('payment')->getInfoBlock($order->getPayment())
				->setIsSecureMode(true);
			$paymentBlock->getMethod()->setStore($storeId);
			$paymentBlockHtml = $paymentBlock->toHtml();
		} catch (Exception $exception) {
			// Stop store emulation process
			$appEmulation->stopEnvironmentEmulation($initialEnvironmentInfo);
			throw $exception;
		}
		
		// Stop store emulation process
		$appEmulation->stopEnvironmentEmulation($initialEnvironmentInfo);
		
		// Retrieve corresponding email template id and customer name
		$templateId = Mage::getStoreConfig(self::XML_PATH_EMAIL_TEMPLATE, $storeId);
		if ($order->getCustomerIsGuest()) {
			$customerName = $order->getBillingAddress()->getName();
		} else {
			$customerName = $order->getCustomerName();
		}
		
		$mailer = Mage::getModel('core/email_template_mailer');
		$emailInfo = Mage::getModel('core/email_info');
		$emailInfo->addTo($order->getCustomerEmail(), $customerName);
		$mailer->addEmailInfo($emailInfo);
		
		// Set all required params and send emails
		$mailer->setSender(Mage::getStoreConfig(self::XML_PATH_EMAIL_SENDER, $storeId));
		$mailer->setStoreId($storeId);
		$mailer->setTemplateId($templateId);
		$mailer->setTemplateParams(array(
			'order'        => $order,
			'billing'      => $order->getBillingAddress(),
			'payment_html' => $paymentBlockHtml
		));
		$mailer->send();
	}
}
